package com.xxgc.demo.controller.error;

import cn.hutool.extra.mail.MailUtil;
import com.xxgc.demo.controller.aop.DataSourceMangerAOP;
import com.xxgc.demo.controller.error.myerror.IdCardDateException;
import com.xxgc.demo.controller.error.myerror.UserPhoneAlreadyExistsException;
import com.xxgc.demo.controller.result.Result;
import com.xxgc.demo.utils.SendEmailToDevOpsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.net.SocketTimeoutException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: SJY
 * @Date :2023/9/8 - 09 - 08 - 14:37
 * 全局异常拦截器 @ControllerAdvice
 */
@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    //邮件通知工具类
    @Autowired
    private SendEmailToDevOpsUtil sendEmailToDevOpsUtil;


    //参数校验的拦截
    @ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
    public ResponseEntity<Result> handleValidatedException(Exception e) {
        Result<List<String>> result = null;
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            List<String> errorMessages = ex.getBindingResult().getAllErrors().stream()
                    .map(ObjectError::getDefaultMessage)
                    .collect(Collectors.toList());
            result = Result.error(HttpStatus.BAD_REQUEST.value(), errorMessages);
        } else if (e instanceof ConstraintViolationException) {
            ConstraintViolationException ex = (ConstraintViolationException) e;
            List<String> errorMessages = ex.getConstraintViolations().stream()
                    .map(ConstraintViolation::getMessage)
                    .collect(Collectors.toList());
            result = Result.error(HttpStatus.BAD_REQUEST.value(), errorMessages);
        } else if (e instanceof BindException) {
            BindException ex = (BindException) e;
            List<String> errorMessages = ex.getAllErrors().stream()
                    .map(ObjectError::getDefaultMessage)
                    .collect(Collectors.toList());
            result = Result.error(HttpStatus.BAD_REQUEST.value(), errorMessages);
        }
        return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
    }

    //参数转换
    @ExceptionHandler(value = {HttpMessageNotReadableException.class})
    public ResponseEntity<Result> httpMessageNotReadableException(Exception e) {
        return new ResponseEntity<>(Result.error().msg("参数类型转换失败").errorMsg(e.getMessage()), HttpStatus.BAD_REQUEST);
    }


    //身份证异常报错
    @ExceptionHandler(value = {IdCardDateException.class})
    public ResponseEntity<Result> idCardDateException(IdCardDateException e) {
        return new ResponseEntity<>(
                Result.error()
                .code(400)
                .msg("请求失败")
                .data(new String[]{e.getErrorMsg()}), HttpStatus.BAD_REQUEST);
    }

    //手机号已存在保存
    @ExceptionHandler(value = {UserPhoneAlreadyExistsException.class})
    public ResponseEntity<Result> userPhoneAlreadyExistsException(UserPhoneAlreadyExistsException e) {
        return new ResponseEntity<>(
                Result.error()
                        .code(400)
                        .msg("请求失败")
                        .data(new String[]{"手机号已被注册"}), HttpStatus.BAD_REQUEST);
    }

    //数据库报错
    @ExceptionHandler(value = {SocketTimeoutException.class})
    public ResponseEntity<Result> SocketTimeoutException(SocketTimeoutException e) {

        //给运维人员或开发人员发送邮件提示
        //sendEmailToDevOpsUtil.sendEmailToDevOps(1,"数据库主库异常，正在进行主备切换，请立即验证是否切换成功",e,true);

        //调用切换数据源完成数据库切换
        String source = DataSourceMangerAOP.getSource();
        source = "standby".equals(source) ? "master" : "standby";
        DataSourceMangerAOP.changeSource(source);

        return new ResponseEntity<>(
                Result.error()
                        .code(500)
                        .msg("请求失败"), HttpStatus.INTERNAL_SERVER_ERROR);
    }





    /**------------------------ 一定写在最下面 ----------------------------------**/
    /**------------------@TODO 开发环境和测试环境不用 只在生产环境用 留坑 （虚竹）-------------------**/
    //运行时的异常
   /* @ExceptionHandler(value = {Exception.class})
    public ResponseEntity<Result> runException(Exception e) {
        log.error(e.getMessage());
        return new ResponseEntity<>(Result.error().msg("当前服务器压力大，请稍后重试"), HttpStatus.INTERNAL_SERVER_ERROR);
    }
*/
}
